package com.example.demoshardingjdbc.web;

import com.example.demoshardingjdbc.domain.Order;
import com.example.demoshardingjdbc.repository.OrderRepository;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import io.shardingsphere.core.keygen.KeyGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HomeController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private KeyGenerator keyGenerator;

    @Autowired
    private OrderRepository orderRepository;

    @GetMapping({"", "index"})
    public String index(Model model) {

        List<Order> list = orderRepository.findAll();
        model.addAttribute("list", list);
        return "index";
    }


    @GetMapping("create")
    public Object create() {

        Order order = new Order();
        order.setOrderId(keyGenerator.generateKey().longValue());
        order.setUserId(keyGenerator.generateKey().longValue());

        orderRepository.save(order);
        return "redirect:/index";
    }

    @GetMapping("list")
    @ResponseBody
    public List<Order> list() {
        try {
            List<Order> list = orderRepository.findAll();
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new ArrayList<>();
    }
    @GetMapping("/del/{orderId}")
    public String del(@PathVariable Long orderId){

        orderRepository.deleteById(orderId);
        return "redirect:/index";
    }

    @GetMapping("page")
    @ResponseBody
    public Object page(){
        Pageable pageable = PageRequest.of(1,20);

        Page<Order> page = orderRepository.findAll(pageable);
        return page;
    }

    @GetMapping("count")
    @ResponseBody
    public Long count(){
        return orderRepository.count();
    }

    @GetMapping("sessions")
    @ResponseBody
    public String sessions(HttpServletRequest request) {

        String sessionID = request.getSession().getId();
        HttpSession session = request.getSession();
        session.setAttribute("userId", "1234");
        return sessionID;
    }

    @GetMapping("sessionUserId")
    @ResponseBody
    public String sessionUserId(HttpServletRequest request,HttpSession session){
        String userId = (String) session.getAttribute("userId");
        return userId;
    }
}
